package com.spc.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.spc.constant.MessageConstant;
import com.spc.entity.Result;
import com.spc.pojo.OrderSetting;
import com.spc.service.OrderSettingService;
import com.spc.utils.POIUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ordersetting")
public class OrderSettingController {
    @Reference
    private OrderSettingService orderSettingService;

    //文件上传，设置预约设置数据批量导入
    @RequestMapping("/upload")
    public Result upload(@RequestParam MultipartFile excelFile){
        try {
            //使用POI解析数据
            List<String[]> list = POIUtils.readExcel(excelFile);
            //修改数据格式
            List<OrderSetting> data = new ArrayList<OrderSetting>();
            for (String[] strings : list) {
                OrderSetting orderSetting = new OrderSetting(new Date(strings[0]), Integer.parseInt(strings[1]));
                data.add(orderSetting);
            }
            //调用服务批量导入到数据库
            orderSettingService.add(data);

        } catch (IOException e) {
            e.printStackTrace();
            //解析失败
            return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
        return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
    }

    //文件上传，设置预约设置数据批量导入
    @RequestMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(String date){
        try {
            //调用服务批量导入到数据库
            List<Map> list = orderSettingService.findByDate(date);
            return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
            //解析失败
            return new Result(false, MessageConstant.GET_ORDERSETTING_FAIL);
        }
    }

    //文件上传，设置预约设置数据批量导入
    @RequestMapping("/editNumberByDate")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting){
        try {
            orderSettingService.editNumberByDate(orderSetting);
            return new Result(true, MessageConstant.ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            //解析失败
            return new Result(false, MessageConstant.ORDERSETTING_FAIL);
        }
    }

}
